package com.smbms.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.smbms.entity.Role;
import com.smbms.entity.User;
import com.smbms.service.role.RoleService;
import com.smbms.service.user.UserService;
import com.smbms.tool.ExcelUtil;
import com.smbms.tool.PageSupport;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	private String downUserName;
	
	private Integer downUserRole = 0;
	
	/**
	 * 进入登录页面
	 * @return
	 */
	@RequestMapping("toLogin")
	public String toLogin(){
		return "login";
	}
	
	/**
	 * 登录处理
	 * @param userCode
	 * @param userPassword
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("login")
	public String login(String userCode,String userPassword,Model model,HttpSession session){
		User user = userService.login(userCode);
		if(user==null){
			model.addAttribute("error","账号不存在！");
			return "login";
		}
		if(!user.getUserPassword().equals(userPassword)){
			model.addAttribute("error","密码不正确！");
			return "login";
		}
		session.setAttribute("userSession", user);
		return "frame";
	}
	
	/**
	 * 退出登录
	 * @param session
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpSession session){
		session.removeAttribute("session");
		return "login";
	}
	
	/**
	 * 分页显示用户列表
	 * @param queryname
	 * @param queryUserRole
	 * @param pageIndex
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("list")
	public String list(String queryname,String queryUserRole,String pageIndex,HttpServletRequest request) throws IOException{
		//查询所有用户
    	int userRole=0;//角色
    	if(queryUserRole!=null){
    		userRole=Integer.valueOf(queryUserRole);
    		downUserRole = Integer.valueOf(queryUserRole);
    	}
    	downUserName = queryname;
    	int currentPageNo=1;//当前页码
    	if(pageIndex!=null){
    		currentPageNo=Integer.valueOf(pageIndex);
    	}
    	int pageSize=5;//页面的大小
    	int currentNo=(currentPageNo-1)*pageSize;//起始数字
    	List<User> userList=userService.getUserList(queryname, userRole, currentNo, pageSize);
    	
    	
    	
    	
    	
    	
    	request.setAttribute("userList", userList);
    	//查询所有角色
    	List<Role> roleList=roleService.getRoleAll();
    	request.setAttribute("roleList", roleList);
    	//返回查询的值
    	request.setAttribute("queryUserName", queryname);
    	request.setAttribute("queryUserRole", userRole);
    	//总记录数
    	PageSupport page=new PageSupport();
    	 page.setPageSize(pageSize);
    	 page.setCurrentPageNo(currentPageNo);
    	 int totalCount=userService.count(queryname, userRole);//查询总记录数
    	 page.setTotalCount(totalCount);
    	 int totalPageCount=page.getTotalPageCount();//查询总页数
    	 //查询的条数
    	 request.setAttribute("totalCount", totalCount);
    	 //当前页码
    	 request.setAttribute("currentPageNo", currentPageNo);
    	 //总页码
    	 request.setAttribute("totalPageCount", totalPageCount);
    	return "userlist";
	}

	
	/**
	 * 去到添加用户页面
	 * @return
	 */
	@RequestMapping("toAdd")
	public String toAdd(){
		return "useradd";
	}
	
	/**
	 * 添加用户
	 * @param user
	 * @param session
	 * @param model
	 * @param img
	 * @return
	 */
	@RequestMapping("add")
	public String add(User user,HttpSession session,Model model,@RequestParam(value="_idPicPath",required=false)MultipartFile[] img){

		String idPicPath = null;
		String workPicPath = null;

		String str = File.separator+"statics"+File.separator+"uploadfiles";
		String path = session.getServletContext().getRealPath(str);

		for (int i = 0; i < img.length; i++) {
			//判断文件是否为空
			if(!img[i].isEmpty()){




				String oldFileName = img[i].getOriginalFilename();//原文件名

				String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀

				int fileSize = 500000;//文件大小

				if(img[i].getSize()>fileSize){//限制文件大小
					model.addAttribute("error", "文件太大了");
					return "useradd";

				}else if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("jpeg")||suffix.equalsIgnoreCase("pneg")){
					String fileName = UUID.randomUUID().toString()+".jpg";
					File file = new File(path, fileName);
					if(!file.exists()){
						file.mkdirs();
					}

					//保存
					try {
						img[i].transferTo(file);
						if(i == 0){
							idPicPath = path+File.separator+fileName;
						}else if(i == 1){
							workPicPath = path+File.separator+fileName;
						}
						
						
						//System.out.println("idPicPath"+idPicPath);
					} catch (Exception e) {
						model.addAttribute("error", "上传失败");
						e.printStackTrace();
						return "useradd";
					}
				}else{
					model.addAttribute("error", "图片格式不正确");
					return "useradd";
				}
			}
		}





		User user1 = (User)session.getAttribute("userSession");
		user.setCreatedBy(user1.getId());
		user.setCreationDate(new Date());
		user.setIdPicPath(idPicPath);
		user.setWorkPicPath(workPicPath);
		boolean flag = userService.addUser(user);
		if(flag){
			return "redirect:list";
		}
		return "useradd";
	}

	@RequestMapping("view")
	@ResponseBody
	public Object view(String id){
		int idInt = Integer.parseInt(id);
		User user = userService.getUserById(idInt);
		return user;
	}


	@RequestMapping(value="boolUserCode")
	@ResponseBody
	public Object boolUserCode(String userCode){
		Map<String, String> map = new HashMap<String,String>();
		User user = userService.selectUserCodeExist(userCode);
		if(user!=null){
			map.put("userCode", "exist");
		}else{
			map.put("userCode", "noexist");
		}
		return map;
	}


	@RequestMapping(value="getRoles")
	@ResponseBody
	public Object getRoles(){
		List<Role> roles = roleService.getRoleAll();
		return roles;
	}
	

	@RequestMapping("toModify")//去到修改页面
	public String toMadify(String uid,HttpServletRequest request){
		int idInt = Integer.parseInt(uid);
		request.setAttribute("user", userService.getUserById(idInt));
		return "usermodify";
	}
	@RequestMapping("modify")//修改用户
	public String modify(User user,HttpSession session){
		User user1 = (User)session.getAttribute("userSession");
		
		user.setModifyBy(user1.getId());
		user.setModifyDate(new Date());
		boolean bool=userService.updateUser(user);
		if(bool){
		return "redirect:list";
		}
		return "usermodify";
	}
	
	/**
	 * 删除用户
	 * @param uid
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(String uid){
		int id = Integer.parseInt(uid);
		boolean flag = userService.deleteUser(id);
		return flag;
	}
	
	@RequestMapping("download")     
    public ResponseEntity<byte[]> download(HttpServletRequest req) throws IOException { 
    	
    	
    	List<User> userList = userService.download(downUserName, downUserRole);
		//下载先把数据写入excel表格
    	String path = new ExcelUtil().writerExcel(userList );
    	
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String(path.getBytes("gbk"),"iso-8859-1");//为了解决中文名称乱码问题  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }

	
}
